package com.tiancheng.trade.order.mq.producer;

import com.tiancheng.trade.commom.core.data.MessageBody;
import com.tiancheng.trade.order.configuration.CallbackConfig;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @author kellen
 * @description 推送支付中心消息生产者
 * @date 2024/12/29 23:39
 */
@Component
@Slf4j
public class OrderStatus2OrderMsgProducer {

    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private MessageConverter messageConverter;
    @Resource
    private CallbackConfig callbackConfig;

    public void sendMessage(MessageBody result,long delay) {
        String routingKey=null;
        try {
            routingKey= result.getRoutingKey();
            rabbitTemplate.convertAndSend(
                    callbackConfig.getExchange(),
                    routingKey,
                    result,
                    message -> {
                        message.getMessageProperties().setHeader("x-retry-count", 0);
                        // 添加消息追踪ID
                        message.getMessageProperties().setCorrelationId(UUID.randomUUID().toString());
                        return message;
                    });

            log.info("支付回调消息已发送 [routingKey:{}][messageId:{}]",
                    routingKey, result.getMessageId());

        } catch (IllegalArgumentException e) {
            log.error("无效的业务编码: {}", routingKey);
            // 可持久化到数据库进行人工处理
            saveErrorRecord(routingKey, result, e.getMessage());

        } catch (AmqpException e) {
            log.error("MQ消息发送失败 [bizCode:{}]", routingKey, e);
            // 触发本地重试或记录错误
            handleSendFailure(routingKey, result, e);
        }
    }

    // 异常处理示例方法
    private void saveErrorRecord(String bizCode, MessageBody result, String error) {
        // 实现持久化逻辑
    }

    // 异常处理示例方法
    private void handleSendFailure(String bizCode, MessageBody result, Exception e) {
        // 实现持久化逻辑
        //log.error("");
    }


    private CallbackConfig.BizConfig getConfigByRoutingKey(String routingKey) {
        return callbackConfig.getConfigs().stream()
                .filter(c -> c.getRoutingKey().equals(routingKey))
                .findFirst()
                .orElseThrow(() -> new RuntimeException(
                        "未找到业务系统配置: " + routingKey));
    }
}
